import axios from 'axios'
import store from '@/store'
import router from '@/router';
import { MessageBox, Notification } from 'element-ui'

// 创建axios实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 60000 // 请求超时时间（毫秒）
})

// request请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = store.getters.token;
    }
    return config;
  },
  error => {
    Notification.error({ title: '错误', message: error });
    return Promise.reject(error);
  }
)

// respone响应拦截器
service.interceptors.response.use(
  response => {
    const { status, data } = response;
    if (status === 200) {
      if (data.code !== 0) {
        Notification.error({ title: '错误', message: data.msg });
        return Promise.reject(new Error(data.msg));
      } else {
        return data;
      }
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    const { status, data } = error.response;
    switch (status) {
      case 401:
        MessageBox.confirm(data.msg, '登陆提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('manager/resetToken').then(() => {
            location.reload();
          })
        });
        break;
      case 403:
        router.push({ path: '/403', query: { msg: data.msg } });
        break;
      case 404:
        router.push({ path: '/404', query: { msg: data.msg } });
        break;
      default:
        Notification.error({ title: status, message: data.msg || 'error' });
        break;
    }
    return Promise.reject(new Error(data.msg || 'error'));
  }
)

export default service
